package com.lijz.interceptor;

import com.lijz.annotation.AuthIgnore;
import com.lijz.constants.Constants;
import com.lijz.utils.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.security.auth.message.AuthException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;

/**
 * @author lijingzhao
 * @date 2018/10/24 20:30
 * 判断是否登录认证拦截器
 */
@Configuration
public class AuthorizationInterceptor implements HandlerInterceptor {

	@Autowired
	private RedisUtil redisUtil;

	@Override
	public boolean preHandle(HttpServletRequest request,
							 HttpServletResponse response, Object handler) throws Exception {
		Method method;
		if (handler instanceof HandlerMethod) {
			HandlerMethod handlerMethod = (HandlerMethod) handler;
			method = handlerMethod.getMethod();
		} else {
			return true;
		}
		AuthIgnore annotation = method.getAnnotation(AuthIgnore.class);

		//如果有@AuthIgnore注解，则不验证token
		if (annotation != null) {
			return true;
		}

		//获取用户凭证
		String token = request.getParameter(Constants.TOKEN);
		Object hgetUserId = redisUtil.hget(Constants.TOKEN_ + token, Constants.USERID);

		//token凭证为空
		if (hgetUserId == null)
			throw new AuthException("请登录！");

		return true;
	}

}
